import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spendbook/common/http.dart';
import 'package:spendbook/models/model.dart';

class User extends Model<User> with ChangeNotifier {
  User();

  User.fromTheme(this._themeMode);

  @override
  String url = '/user';

  String _themeMode = 'dark';

  String nickname = '';

  String phone = '';

  String deviceId = '';

  String pushId = '';

  bool needBiometrics = false;

  bool get isDarkTheme {
    return _themeMode == 'dark';
  }

  Future<void> logout() async {
    this.id = 0;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('user');
    notifyListeners();
  }

  Future<void> login() async {
    fromJson(await httpPost('/login', toJson()));
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('user', JsonEncoder().convert(toJson()));
    notifyListeners();
  }

  Future<void> exist() async {
    try {
      fromJson(await httpGet('/login?device_id=${deviceId.toString()}'));
    } on HttpException catch (_) {}
  }

  set themeMode(String _theme) {
    _themeMode = _theme;
    notifyListeners();
  }

  String get themeMode {
    return this._themeMode;
  }

  get isLogin {
    return id != null && id! > 0;
  }

  @override
  Map<String, dynamic> toJson() => {'nickname': nickname, 'phone': phone, 'deviceId': deviceId, 'pushId': pushId}..addAll(super.toJson());

  @override
  void fromJson(Map<String, dynamic> json) {
    nickname = json['nickname'] ?? '';
    phone = json['phone'] ?? '';
    deviceId = json['deviceId'] ?? '';
    pushId = json['pushId'] ?? '';
    super.fromJson(json);
  }

  @override
  bool checkFetch() => phone == '';

  @override
  void afterStore() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('user', JsonEncoder().convert(toJson()));
  }
}
